'''
@author: philip
'''

from events.models import event, event_winner
from django.core.exceptions import ObjectDoesNotExist
from datetime import date, timedelta

class events_repository():
    def __init__(self):
        pass
    
    def get_events_scheduled_for_today(self):
        yesterday = date.today() - timedelta(1)
        tomorrow = date.today() + timedelta(1)
        
        return list(event.objects.filter(when__gt=yesterday).
                    filter(when__lt=tomorrow))
        
    def get_upcoming_events(self):
        return event.objects.exclude(status='over')
    
    def get_upcoming_events_for_surfer(self,surfer_id):
        return event.objects.filter(participants=surfer_id).exclude(status='over')
    
    def get_event_details(self,id):
        try:
            return event.objects.get(id=id)
        except ObjectDoesNotExist:
            return None
    
    def update_event(self,event):
        event.save()
        
    def add_event_participant(self, event_id, participant_id):
        try:
            e = event.objects.get(id=event_id)
        except ObjectDoesNotExist: return None
        
        e.participants.append(participant_id)
        e.save()
        return event
    
    def get_winner_by_id(self, winner_id):
        try:
            return event_winner.objects.get(id=winner_id)
        except ObjectDoesNotExist: return None
        
    def get_winners_for_event(self,event_id):
        return list(event_winner.objects.filter(event_id=event_id))
    
    def get_winners_by_user(self,user_id):
        return list(event_winner.objects.filter(participant_id=user_id))
    
    def add_event_winner(self,event_id,participant_id,place):
        new_event_winner = event_winner()
        new_event_winner.event_id = event_id
        new_event_winner.participant_id = participant_id
        new_event_winner.place = place
        new_event_winner.save()
        return new_event_winner
    
    def update_event_winner(self, winner):
        winner.save()